package com.scheuk.euler;

import java.util.Map.Entry;
import java.util.TreeMap;

/**
 * A palindromic number reads the same both ways. The largest palindrome 
 * made from the product of two 2-digit numbers is 9009 = 91 99.
 * Find the largest palindrome made from the product of two 3-digit numbers.
 * Answer: 913 * 993 = 906609
 * 
 * @author scheuk
 *
 */
public class p004 {
	
	public static TreeMap<Integer, String> lookup = new TreeMap<Integer, String>();
	
	public static void findPalindromes(int[] limits)
	{
		for (int i = limits[0]; i > limits[1]; i--)
		{
			for (int j = limits[0]; j > limits[1]; j--)
			{
				int product = i*j;
				if (isPalindrome(product))
				{
					lookup.put(product, i + " * " + j);
				}
			}
		}
	}
	
	private static boolean isPalindrome(int num)
	{
		char[] c = Integer.toString(num).toCharArray();
		int mid = c.length/2;
		int end = c.length-1;
		for (int i = 0; i <= mid; i++)
		{
			if (c[i] != c[end]) return false;
			end--;
		}
		return true;
	}
	
	private static int[] setup(int length)
	{
		StringBuffer s = new StringBuffer();
		int[] limits = new int[2];
		for (int i = 0; i < length; i++)
		{
			s.append("9");
		}
		System.out.println("upper limit : " + s);
		limits[0] = Integer.parseInt(s.toString());
		s = s.deleteCharAt(s.length()-1);
		System.out.println("lower limit : " + s);
		limits[1] = Integer.parseInt(s.toString());
		return limits;
	}
	
	public static String getLargestPalindrome(int length)
	{
		
		findPalindromes(setup(length));
		Entry<Integer, String> result = lookup.lastEntry();
		String s = result.getValue() + " = " + result.getKey();
		return s;
	}
	
	public static void main(String[] args)
	{
		System.out.println(getLargestPalindrome(3));
	}

}
